package tw.asap.plus.ui.activity;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.entity.request.ShopRequestBean;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.MerchantService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.adapter.MerchantListAdapter;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.utils.SPUtil;
import tw.asap.plus.utils.T;

/**
 * Description:
 * Created:      [15/11/11]
 * Author:       [Yang]
 **/
public class MerchantListActivity extends AsapBaseActivity {

    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.rv_base_list_fragment)
    RecyclerView recyclerView;
    @InjectView(R.id.srl_base_list_fragment)
    SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.extra_layout)
    FrameLayout extraLayout;
    private ArrayList<ShopIndex.ShopEntity> dataList = new ArrayList<>();
    private MerchantListAdapter adapter;
    private int currentPage;
    String sccode;
    String categoryName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant_list);
        ButterKnife.inject(this);
        appbar.setLeftClickEvent(v -> finish());
        extraLayout.setOnClickListener(v -> {
            displayExtraLayout(0);
            reload(true);
        });
        displayExtraLayout(0);
        sccode = getIntent().getStringExtra("SCCODE");
        categoryName = getIntent().getStringExtra("CATEGORY_NAME");
        appbar.setTitle(categoryName);
        reload(false);
    }

    public void reload(boolean isBackground) {
        if (swipeRefreshLayout != null && !isBackground)
            swipeRefreshLayout.setRefreshing(true);
        currentPage = 0;

        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<ShopIndex.ShopEntity>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<ShopIndex.ShopEntity>>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);
                String lat = SPUtil.getInstance(MerchantListActivity.this).getString(ConstValue.Sp.LAT, "0");
                String lng = SPUtil.getInstance(MerchantListActivity.this).getString(ConstValue.Sp.LNG, "0");
                ResponseDataWrapper<List<ShopIndex.ShopEntity>> responseDataWrapper = service.getMerchantList(new ShopRequestBean(lat, lng, sccode));
                subscriber.onNext(responseDataWrapper);
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<ShopIndex.ShopEntity>>>() {
                               @Override
                               public void onCompleted() {
                               }

                               @Override
                               public void onError(Throwable e) {
                                   if (swipeRefreshLayout != null && !isBackground) {
                                       swipeRefreshLayout.setRefreshing(false);
                                   }
                                   T.e(e.toString());
                                   displayExtraLayout(2);
                               }

                               @Override
                               public void onNext(ResponseDataWrapper<List<ShopIndex.ShopEntity>> responseDataWrapper) {
                                   if (swipeRefreshLayout != null && !isBackground)
                                       swipeRefreshLayout.setRefreshing(false);
                                   if (responseDataWrapper.respcd.equals(ConstValue.RESPCD)) {
                                       if (responseDataWrapper.data.size() == 0) {
                                           displayExtraLayout(1);
                                       } else {
                                           if (adapter == null) {
                                               dataList.addAll(responseDataWrapper.data);
                                               initRecyclerView(dataList);
                                           } else {
                                               dataList.clear();
                                               dataList.addAll(responseDataWrapper.data);
                                           }
                                           adapter.notifyDataSetChanged();
                                       }
                                   }
                               }
                           }

                );
    }

    private void initRecyclerView(List<ShopIndex.ShopEntity> list) {
        extraLayout.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        adapter = new MerchantListAdapter(this, list);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);
    }

    private void displayExtraLayout(int type) {
        if (extraLayout.getChildCount() > 0) {
            extraLayout.removeAllViews();
        }
        extraLayout.setVisibility(View.VISIBLE);
        switch (type) {
            case 0://loading
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(this).inflate(R.layout.layout_loading, extraLayout);
                break;
            case 1://noData
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(this).inflate(R.layout.layout_nodata, extraLayout);
                break;
            case 2://noNetwork
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(this).inflate(R.layout.layout_nonetwork, extraLayout);
                break;
        }
    }
}
